#region Imported Namespaces
using System;
using System.Collections;
using System.Collections.Specialized;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Data;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.Design;
using System.Web.UI.WebControls;

using PHSRAG.Insight21.SearchContext;
using DataAccess = PHSRAG.Utility.DataAccess;
using SessionCachePolicy = PHSRAG.Insight21.Policy.SessionCachePolicy;
using Policy = PHSRAG.Insight21.Policy;
using UserContext = PHSRAG.Insight21.Context.UserContext;
using Constants = PHSRAG.Insight21.InsightUtilities.Constants;
using PHSRAG.Insight21.CDS;
using PHSRAG.Insight21.COI;


#endregion

namespace PHSRAG.Insight21.InsightWebControls
{
	#region Class COISearch
	/// <summary>
	/// The COISearch control is used by COI summary pages(Supervisor summary and Hierarchy maintenance).
	/// </summary>
	[ToolboxData("<{0}:COISearch runat=server />"), Designer(typeof(COISearchDesigner))]
	public class COISearch: BaseSearch, INamingContainer, ISearch
	{
		#region constants
		private const string ViewOptionVisibilityKey="viewOptionVisibility_AB597720-B7B6-4177-8637-6763B03DCF36";
		private const string ViewExternalUsersVisibilityKey="viewExternalVisibility_AB597720-B7B6-4177-8637-6763B03DCF36";
        private const string ShowHierarchyTypeKey = "ShowHierarchyType_FA6B3693-7A6A-4d11-96E6-C0DE4CC7A128";
        private const int defaultSelectedIndex=-1;//None selected by default(for ListBox)
		#endregion

		#region Instance Variables
		private Policy.ICachePolicy	cachePolicy;
		private TextBox			    firstName;
		private TextBox			    lastName;
		private TextBox			    userName;
		private CheckBox			policyQuestion;
		private CheckBox			nothingToDisclose;
		private CheckBox			includeAll;
		private CheckBox			directReportsOnly;
		private CheckBox			externalPeople;
		private ListBox			    statusList;
        private TextBox             supervisorLastName;
        private TextBox             supervisorFirstName;
		private ControlCollection	controlCollection;
        private DropDownList        HierarchyType;
		#endregion

		#region ISearch Members
		/// <summary>
		/// Reset the internal search state. This involves setting the value for all controls to their default values
		/// and resetting the cached state of the search context.
		/// </summary>
		public void Reset()
		{
			ResetControls(controlCollection);			
			COISearchContext searchContext = (COISearchContext)cachePolicy.GetCachedObject(COISearchContext.CacheKey);
			searchContext.Reset(Page.Request.Url.ToString());
		}
		/// <summary>
		/// Get/Set the visibility of the View Option drop-down-list.
		/// </summary>
		
		public bool ViewOptionVisible
		{
			get { object o = ViewState[ViewOptionVisibilityKey]; return (o == null) ? true : (bool)o; }
			set { ViewState[ViewOptionVisibilityKey] = value; }
		}

        public bool ShowHierarchyType
        {
            get { object o = ViewState[ShowHierarchyTypeKey]; return (o == null) ? true : (bool)o; }
            set { ViewState[ShowHierarchyTypeKey] = value; }
        }

		public bool ViewExternalUsersVisible
		{
			get { object o = ViewState[ViewExternalUsersVisibilityKey]; return (o == null) ? false : (bool)o; }
			set { ViewState[ViewExternalUsersVisibilityKey] = value; }
		}

        private COIUser.HierarchyType intDefaultHierarchyType = COIUser.HierarchyType.Institutional;
        public COIUser.HierarchyType DefaultHierarchyType
        {
            get { return intDefaultHierarchyType; }
            set { intDefaultHierarchyType = (COIUser.HierarchyType)value; }
        }
        //private int intDefaultHierarchyType = (int)COIUser.HierarchyType.Institutional;
        //public int DefaultHierarchyType
        //{
        //    get { return intDefaultHierarchyType; }
        //    set { intDefaultHierarchyType = value; }
        //}
		/// <summary>
		/// Get the search criteria from the common search context.
		/// </summary>
		public SearchCriteria SearchCriteria
		{
			get
			{
				return ((COISearchContext)cachePolicy.GetCachedObject(COISearchContext.CacheKey)).GetSearchCriteria(Page.Request.Url.ToString());
			}
		}


		/// <summary>
		/// Get the search criteria. This is done by collecting the current values in all controls, storing them in the
		/// COISearchContext, and then returning the search criteria.
		/// </summary>
		public SearchCriteria UpdateSearchCriteria()
		{
			UserContext userContext = (UserContext)cachePolicy.GetCachedObject(UserContext.CacheKey);
			return GetSearchCriteria(userContext.DomainUserId, controlCollection);
		}
		#endregion

		#region Protected Properties
		/// <summary>
		/// Determine if the control is in design mode. It is if there is not HTTP context.
		/// </summary>
		protected static bool IsDesignMode
		{
			get { return HttpContext.Current == null; }
		}
		#endregion

		#region
		/// <summary>
		/// Invoked by the method which builds the HTML representation of the control tree. Derived classes would typically
		/// return the HTML to be inserted into the stream AFTER the indicated row.
		/// </summary>
		/// <param name="currentRowNumber">The number (starting from 1) of the row that the HTML returned by this method
		/// would be inserted at.
		/// </param>
		/// <returns>HTML string to add at row number currentRowNumber</returns>
		protected virtual string GetHTML(int currentRowNumber)
		{
			return string.Empty;
		}
		#endregion 

		#region Overrides
		/// <summary>
		/// Create all controls. Notice that the creation is more than just instantiating the controls. It also involves
		/// in generating the underlying HTML so that the controls shows up per the need.
		/// </summary>
		protected override void CreateChildControls()
		{
			CreateControls();
			GenerateControlTree();
		}

		/// <summary>
		/// Initializes the cachepolicy. Create and cache a COISearchContext object if necessary.
		/// Note that controls whose state must persist in the view state MUST be created BEFORE OnInit completes. We do
		/// this simply by invoking EnsureChildControls().
		/// </summary>
		/// <param name="e">Argument associated with the event</param>
		protected override void OnInit(EventArgs e)
		{
			cachePolicy = (Policy.ICachePolicy)Page.Session[Policy.Names.CachePolicyKey];
			COISearchContext searchContext = cachePolicy.GetCachedObject(COISearchContext.CacheKey) as COISearchContext;
			if (searchContext == null)
			{
				searchContext = new COISearchContext(cachePolicy);
				searchContext.Load(DataAccess.ConnectionString);
				searchContext.Cache();
			}
			EnsureChildControls();
			base.OnInit(e);
			searchContext.GetSearchCriteria(Page.Request.Url.ToString(), controlCollection);
		}
		/// <summary>
		/// Initialize the contents of all controls on first load. If the PersonnelSearchContext is not cached yet, a
		/// new instance is created and cached. 
		/// </summary>
		/// <param name="e">Argument associated with the event</param>
		protected override void OnLoad(EventArgs e)
		{
			cachePolicy = (Policy.ICachePolicy)Page.Session[Policy.Names.CachePolicyKey];

			if (!Page.IsPostBack)
			{
				COISearchContext searchContext = cachePolicy.GetCachedObject(COISearchContext.CacheKey) as COISearchContext;
                if (ShowHierarchyType)
                {
                    LoadDropdownList(HierarchyType, GetHierarchyTypes(), "Id", "Description", DefaultHierarchyType);
                }
                if(ViewOptionVisible)
				{
					LoadListBoxList(statusList,LoadStatus(),"Code",defaultSelectedIndex);
				}                 
				if (searchContext == null)
				{
                    searchContext = new COISearchContext(cachePolicy);
					searchContext.Load(DataAccess.ConnectionString);
					searchContext.Cache();
				}

				SetControlState(searchContext.GetSearchCriteria(Page.Request.Url.ToString()));
			}
		}
		/// <summary>
		/// Render the control. Note that we simply ensure that all child controls are created, and then delegate the
		/// call back to the base class.
		/// </summary>
		/// <param name="writer">The writer to use for rendering</param>
		protected override void Render(HtmlTextWriter writer)
		{
			EnsureChildControls();
			base.Render(writer);
		}
		#endregion	

		
		#region Private Methods
			
		
		/// <summary>
		/// Create all controls in the CommonSearch.
		/// </summary>
		private void CreateControls()
		{
			Controls.Clear();
			controlCollection = new ControlCollection(this);

			lastName = new TextBox();
			lastName.ID = "LastName";
			lastName.CssClass = "DataInput";
			lastName.Attributes["Label"] = "Last Name";
			controlCollection.Add(lastName);

			firstName = new TextBox();
			firstName.ID = "FirstName";
			firstName.CssClass = "DataInput";
			firstName.Attributes["Label"] = "First Name";
			controlCollection.Add(firstName);			

			userName = new TextBox();
			userName.ID = "UserName";
			userName.CssClass = "DataInput";
			userName.Attributes["Label"] = "User Name";
			controlCollection.Add(userName);

            supervisorLastName = new TextBox();
            supervisorLastName.ID = "supervisorLastName";
            supervisorLastName.CssClass = "DataInput";
            supervisorLastName.Attributes["Label"] = "Supervisor Last Name";
            controlCollection.Add(supervisorLastName);

            supervisorFirstName = new TextBox();
            supervisorFirstName.ID = "supervisorFirstName";
            supervisorFirstName.CssClass = "DataInput";
            supervisorFirstName.Attributes["Label"] = "Supervisor First Name";
            controlCollection.Add(supervisorFirstName);

            if (ShowHierarchyType)
            {
                HierarchyType = new DropDownList();
                HierarchyType.ID = "HierarchyType";
                HierarchyType.CssClass = "FlatDropdown";
                HierarchyType.DataTextField = "Description";
                HierarchyType.DataValueField = "Id";
                controlCollection.Add(HierarchyType);
            }

			if (ViewOptionVisible)
			{
				statusList=new ListBox();
				statusList.ID="statusList";
				statusList.CssClass = "FlatDropdown";
				statusList.DataTextField="Status";
				statusList.SelectionMode=ListSelectionMode.Multiple;
				controlCollection.Add(statusList);		

				policyQuestion = new CheckBox();
				policyQuestion.ID = "policyQuestion";				
				//policyQuestion.Text="Policy Question";
				controlCollection.Add(policyQuestion);

				nothingToDisclose = new CheckBox();
				nothingToDisclose.ID = "nothingToDisclose";
				//nothingToDisclose.Text="Nothing To Disclose";
				controlCollection.Add(nothingToDisclose);	

				includeAll = new CheckBox();
				includeAll.ID = "includeAll";
				//nothingToDisclose.Text="Nothing To Disclose";
				controlCollection.Add(includeAll);

				directReportsOnly = new CheckBox();
				directReportsOnly.ID = "directReportsOnly";
				controlCollection.Add(directReportsOnly);
			}
			if (ViewExternalUsersVisible)
			{
				externalPeople = new CheckBox();
				externalPeople.ID = "externalPeople";
				//nothingToDisclose.Text="Nothing To Disclose";
				controlCollection.Add(externalPeople);	
			}		
		}

		///
		///
		private ArrayList LoadStatus()
		{
			CDS.RefCodes refCodes =
				(CDS.RefCodes)((Policy.ICachePolicy)Page.Application[Policy.Names.ApplicationCachePolicyKey]).GetCachedObject(CDS.RefCodes.CacheKey);

			ArrayList COIStatus =
				(ArrayList)refCodes.GetSortedRefCodes(COI.Constants.COIStatus.Domain,COI.Constants.COIStatus.AttributeOrder);

			return COIStatus;
			
		}


        private DataTable GetHierarchyTypes()
        {
            DataTable dt = DataAccess.GetDataTable(DataAccess.GetConnectionString(), "GetCOIHierarchyTypes", null);
            return dt;

        }
		/// <summary>
		/// Create a table hosted by the first column of the first row of the first table. 
		/// The table contains the following: 
		/// Row 1 Col 1: First Name Label 
		/// Row 1 Col 2: First Name TextBox
		/// Row 1 Col 3: Last Name Label
		/// Row 1 Col 4: Last Name TextBox
		/// Row 1 Col 5: User Name Label
		/// Row 1 Col 6: User Name TextBox 
		/// Row 1 Col 7: Policy Question in Label	
		/// Row 1 Col 8: Policy Question in Checkbox
		/// Row 1 Col 9: Outstanding Reports in Checkbox
		/// </summary>

		private Table GenerateControlTreeForFirstSection()
		{
			Table t = new Table();
			t.CssClass = "Search";
            
			TableRow r1 = new TableRow();
			r1.Width=Unit.Percentage(100);
			t.Rows.Add(r1);

			TableCell r1c1 = new TableCell();
			r1c1.Attributes["align"] = "right";
			r1c1.Text = "<nobr>Last&nbsp;Name:</nobr>"; 
			r1.Cells.Add(r1c1);

			TableCell r1c2 = new TableCell();
			r1.Cells.Add(r1c2);
			r1c2.Controls.Add(lastName);
			
			TableCell r1c3 = new TableCell();
			r1c3.Attributes["align"] = "right";
			r1c3.Text = "<nobr>First&nbsp;Name:</nobr>"; 
			r1.Cells.Add(r1c3);

			TableCell r1c4 = new TableCell();
			r1.Cells.Add(r1c4);
			r1c4.Controls.Add(firstName);

			TableCell r1c5 = new TableCell();
			r1c5.Attributes["align"] = "right";
			r1c5.Text = "<nobr>User&nbsp;Name:</nobr>";
			r1.Cells.Add(r1c5);

			TableCell r1c6 = new TableCell();
			r1.Cells.Add(r1c6);
			r1c6.Controls.Add(userName);

            if (!ViewOptionVisible)
            {
                if (ShowHierarchyType)
                {
                    TableCell r1c9 = new TableCell();
                    r1c9.Attributes["align"] = "right";
                    r1c9.Text = "<nobr>Hierarchy&nbsp;Type:</nobr>";
                    r1.Cells.Add(r1c9);

                    TableCell r1c10 = new TableCell();
                    r1.Cells.Add(r1c10);
                    r1c10.Controls.Add(HierarchyType);
                }
            }

			if (ViewOptionVisible)
			{

				TableCell r1c7 = new TableCell();
				r1c7.Attributes["align"] = "right";
				r1c7.Text = "Status:";
				r1.Cells.Add(r1c7);

				TableCell r1c8 = new TableCell();
				r1.Cells.Add(r1c8);
				r1c8.RowSpan=3;
				//r1c8.Controls.Add(outStandingReports);
				r1c8.Controls.Add(statusList);

				TableRow r2 = new TableRow();
				r2.Width=Unit.Percentage(100);
				t.Rows.Add(r2);

				TableCell r2c1 = new TableCell();
				r2c1.Attributes["align"] = "right";
				r2c1.Text = "Policy Question:"; 
				r2.Cells.Add(r2c1);

				TableCell r2c2 = new TableCell();
				r2.Cells.Add(r2c2);
				r2c2.Attributes["align"] = "left";
				r2c2.Controls.Add(policyQuestion);

				TableCell r2c3 = new TableCell();
				r2c3.Attributes["align"] = "right";
				r2c3.Text = "Nothing to Disclose:"; 
				r2.Cells.Add(r2c3);

				TableCell r2c4 = new TableCell();
				r2.Cells.Add(r2c4);
				r2c4.Attributes["align"] = "left";
				r2c4.Controls.Add(nothingToDisclose);

				TableCell r2c5 = new TableCell();
				r2c5.Attributes["align"] = "right";
				r2c5.Text = "All (Include Inactive):"; 
				r2.Cells.Add(r2c5);

				TableCell r2c6 = new TableCell();
				r2.Cells.Add(r2c6);
				r2c6.Attributes["align"] = "left";
				r2c6.Controls.Add(includeAll);
				TableRow r3 = new TableRow();
				r3.Width=Unit.Percentage(100);
				t.Rows.Add(r3);

				TableCell r3c1 = new TableCell();
				r3c1.Attributes["align"] = "right";
				r3c1.Text = "Direct Reports Only:"; 
				r3.Cells.Add(r3c1);

				TableCell r3c2 = new TableCell();
				r3.Cells.Add(r3c2);
				r3c2.Attributes["align"] = "left";
				r3c2.Controls.Add(directReportsOnly);

                TableCell r3c3 = new TableCell();
                r3c3.Attributes["align"] = "right";
                r3c3.Text = "Supervisor <nobr>Last&nbsp;Name:</nobr>";
                r3.Cells.Add(r3c3);

                TableCell r3c4 = new TableCell();
                r3.Cells.Add(r3c4);
                r3c4.Attributes["align"] = "left";
                r3c4.Controls.Add(supervisorLastName);

                TableCell r3c5 = new TableCell();
                r3c5.Attributes["align"] = "right";
                r3c5.Text = "Supervisor <nobr>First&nbsp;Name:</nobr>";
                r3.Cells.Add(r3c5);

                TableCell r3c6 = new TableCell();
                r3.Cells.Add(r3c6);
                r3c6.Attributes["align"] = "left";
                r3c6.Controls.Add(supervisorFirstName);


                TableRow r4 = null;
				if (ViewExternalUsersVisible)
				{
                    r4 = new TableRow();
                    r4.Width = Unit.Percentage(100);
                    t.Rows.Add(r4);
					TableCell r4c1 = new TableCell();
                    r4c1.Attributes["align"] = "right";
                    r4c1.Text = "Include External People";
                    r4.Cells.Add(r4c1);

					TableCell r4c2 = new TableCell();
                    r4.Cells.Add(r4c2);
                    r4c2.Attributes["align"] = "left";
                    r4c2.Controls.Add(externalPeople);
				}
                if (ShowHierarchyType)
                {
                    if (null == r4)
                    {
                        r4 = new TableRow();
                        r4.Width = Unit.Percentage(100);
                        t.Rows.Add(r4);
                    }
                    TableCell r1c9 = new TableCell();
                    r1c9.Attributes["align"] = "right";
                    r1c9.Text = "<nobr>Hierarchy&nbsp;Type:</nobr>";
                    r4.Cells.Add(r1c9);

                    TableCell r1c10 = new TableCell();
                    r4.Cells.Add(r1c10);
                    r1c10.Controls.Add(HierarchyType);
                }
			}						
			return t;
		}

		/// <summary>
		/// Setup the control tree to reflect the actual (and exact) layout of the controls within the CommonSearch.
		/// </summary>
		private void GenerateControlTree()
		{
			string searchClientId = ((Policy.ICachePolicy)Page.Session[Policy.Names.CachePolicyKey]).GetCachedObject(Constants.SearchButtonClientIDKey) as string;
			if (searchClientId == null)
				searchClientId = "expandingPanel_commonSearch_search";

			Table t1 = new Table();
			t1.CssClass = "Search";
			//t1.CellSpacing = t1.CellPadding = 2;
			t1.Attributes.Add("onkeypress", "return ClickButton(event, '" + searchClientId + "')");
			Controls.Add(t1);

			TableRow t1r1 = new TableRow();
			t1r1.Width=Unit.Percentage(90);
			t1.Rows.Add(t1r1);

			TableCell t1r1c1 = new TableCell();
			t1r1c1.Attributes["valign"] = "top";
			t1r1c1.Width=Unit.Percentage(100);
			t1r1c1.Attributes["align"]="left";
			t1r1.Cells.Add(t1r1c1);
			t1r1c1.Controls.Add(GenerateControlTreeForFirstSection());
		}

		/// <summary>
		/// Helper method to load a drop-down-list with data.
		/// </summary>
		/// <param name="list">Reference to the drop-down-list to load</param>
		/// <param name="table">DataTable which contains data to load</param>
		/// <param name="valueColumnName">Name of the column which holds the value for the row</param>
		/// <param name="selectedIndex">Index of the dropdown which is defaulted to</param>
		private static void LoadListBoxList(ListBox list, ArrayList statusList, string valueColumnName, int selectedIndex)
		{
			
			foreach (RefCode refCode in statusList)
				list.Items.Add(new ListItem((string)refCode.Meaning, refCode.Code));
				list.SelectedIndex = selectedIndex;		

			list.Enabled = (list.Items.Count > 1);
		}


        /// <summary>
        /// Helper method to load a drop-down-list with data.
        /// </summary>
        /// <param name="ddlList">Reference to the drop-down-list to load</param>
        /// <param name="dt">DataTable which contains data to load.</param>
        /// <param name="valueColumnName">Name of the column which holds the value for the row</param>
        /// /// <param name="textColumnName">Name of the column which holds the text for the row</param>
        /// <param name="selectedIndex">Index of the dropdown which is defaulted to</param>
        private static void LoadDropdownList(DropDownList ddlList, DataTable dt, string valueColumnName, string textColumnName, COIUser.HierarchyType enumHierarchyType)
        {
            ddlList.Items.Add(new ListItem("", "0"));
            foreach(DataRow dr in dt.Rows)
            {
                ListItem li = new ListItem(dr[textColumnName].ToString(), dr[valueColumnName].ToString());
                ddlList.Items.Add(li);
                li.Selected = Convert.ToInt32(li.Value) == (int)enumHierarchyType;
            }
            ddlList.Enabled = (ddlList.Items.Count > 1);

        }

        
		#endregion

		#region Internal Methods
		/// <summary>
		/// This method is ONLY invoked by the associated designer to show the control contents at design time.
		/// </summary>
		internal void Design()
		{
			EnsureChildControls();
		}
		#endregion
	}
	#endregion

	#region Class PagerDesigner
	/// <summary>
	/// Designer associated with the COISearch control.
	/// </summary>
	/// <remarks>
	/// This class cannot be used directly.
	/// </remarks>
	public class COISearchDesigner : ControlDesigner
	{
		#region Overrides
		/// <summary>
		/// Force the control to create its child controls for display at design time.
		/// </summary>
		/// <returns>HTML representation of the control</returns>
		public override string GetDesignTimeHtml()
		{
			((COISearch)Component).Design();
			return base.GetDesignTimeHtml();
		}
		#endregion
	}
	#endregion
}

